package com.ah.proj.util;

import java.io.IOException;
import java.lang.reflect.Method;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/ABaseServlet")
public class BaseServlet extends HttpServlet {
	// Servlet的创建和维护，比较消耗资源，是以不宜使用太多的Servlet。
	// 通常，一个模块使用一个Servlet，模块内的业务用url的参数区分——
	// 增加：/?action=add
	// 修改：/?action=upd
	// 删除：/?action=del
	// 查询：/?action=get
	// 模块化的Servlet——传统做法
	// （1）接收参数
	// （2）根据参数值调用相应的方法
	private void doGet_Tradition(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String action = request.getParameter("action");
		if ("add".equals(action)) {
			// add(request, response);
		} else if ("upd".equals(action)) {
			// upd(request, response);
		}
	}

	// 很容易想到的约定：参数名==需要调用的方法名
	// 因此，可以使用反射，将所有的action和方法统一处理，减少代码
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String action = request.getParameter("action");
		Method method;
		try {
			Class<? extends BaseServlet> _servlet = this.getClass();
			Class<HttpServletRequest> _requestClass = HttpServletRequest.class;
			Class<HttpServletResponse> _responseClass = HttpServletResponse.class;
			method = _servlet.getDeclaredMethod(action, _requestClass, _responseClass);
			method.setAccessible(true);
			// 执行
			method.invoke(this, request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}
